package com.cn.ccp.action.course.releaseapproval;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.cn.ccp.action.BaseAction;
import com.cn.ccp.bean.CourseBean;
import com.cn.ccp.bean.CourseContentBean;
import com.cn.ccp.bean.CourseContentManageBean;
import com.cn.ccp.bean.CourseEvaluationBean;
import com.cn.ccp.bean.CourseOutlineBean;
import com.cn.ccp.bean.CourseReleaseRecordBean;
import com.cn.ccp.bean.CoursesApproveBean;
import com.cn.ccp.bean.FilePathBean;
import com.cn.ccp.bean.StudentMarkedHistoryBean;
import com.cn.ccp.bean.UserBean;
import com.cn.ccp.util.CCPContants;
import com.cn.ccp.util.Contants;

/**
 * 老师发布课程审批
 * @author renyongcheng
 *
 */
public class CourseReleaseApprovalAction extends BaseAction {
	private Logger log = Logger.getLogger(CourseReleaseApprovalAction.class);
	private List<CourseBean> courseList ;
	private CourseBean bean ;
	private String approvalOpinion;//审批意见
	
	private List<CoursesApproveBean> approveList ;//审批历史
	
	private List<CourseContentManageBean> courseChapterList ;
	private CourseContentBean courseContentBean ;
	private List<StudentMarkedHistoryBean> markedList;//学生评价历史
	private String courseId,strNextCourseDetailId,strProCourseDetailId;
	private String outline;//课程大纲
	private String courseEva;//课程考核办法
	private boolean showEditOutline = false ;
	private boolean showEditEvaluation = false ;
	
	private int curIndex = -1;//当前课程详细信息索引
	private String[] arrayId;// 课程详细信息id数组
	
	public CourseReleaseApprovalAction(){
		log.info("-------CourseReleaseApprovalAction()-------");
	}

	private void resetOutlineAndEvlaSession(){
		HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		session.removeAttribute(CCPContants.OUTLINE_FILE_PATH);
		session.removeAttribute(CCPContants.EVALUA_FILE_PATH);
		session.removeAttribute(CCPContants.FILE_TYPE);
		showEditEvaluation = true;
		showEditOutline = true;
		curIndex = -1;
	}
	
	/**
	 * 显示审批详细页面
	 * @return
	 */
	public String goApproval(){
		resetOutlineAndEvlaSession();
		Map<String, String> varMap = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
		String id = varMap.get("id");
		bean = getCourseService().getBeanById(id);
		log.info(bean);
		if(bean.getImage()  != null && !"".equalsIgnoreCase(bean.getImage().trim())){
			File sourseFile = null;
			if(bean.getFile_path_id() !=  -1)
				sourseFile = new File(getFilePathService().findFilePathById(bean.getFile_path_id()).getPath()+bean.getImage());
			else
				sourseFile = new File(CCPContants.SYS_PATH+"files"+File.separator + bean.getImage());
			
			File des = new File(CCPContants.SYS_PATH + "tempfile"+File.separator+CCPContants.getUserBean().getId() + File.separator);
			if(des.mkdir()){
				des.mkdirs();
			}
			des = new File(CCPContants.SYS_PATH + "tempfile"+File.separator+CCPContants.getUserBean().getId()  + File.separator +sourseFile.getName());
			CCPContants.copyFile(sourseFile.getPath(), des.getPath());
			bean.setImage(CCPContants.getCurrUserId()+"/"+des.getName());
		}
		markedList = getSelectCourseService().getMarkedList(id);
//		log.info("-------goApproval()-------"+bean);
		Object obj = getCourseService().getCourseApprovalOpinion(id);
		approvalOpinion = obj != null ? obj.toString() : "" ;
		courseChapterList = null;
		
		////
		CourseOutlineBean courseOutLineBean = getCourseService().getOutlineByCourseId(bean.getId());
		if(courseOutLineBean !=null && courseOutLineBean.getOutline() != null && courseOutLineBean.getOutline().endsWith(".txt")){
			showEditOutline = true;
		}else if(courseOutLineBean !=null && courseOutLineBean.getOutline() != null){//其他文件，使用组件显示
			showEditOutline = false; 
			String savePath = getOutlineFilePath();
			savePath += courseOutLineBean.getOutline();
			String outlinePath  = CCPContants.copyOutline(savePath, courseOutLineBean.getOutline(),Contants.OUTLINE_DERECT);
			log.info("------------outlinePath = "+outlinePath);
			HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
			session.setAttribute(CCPContants.OUTLINE_FILE_PATH, courseOutLineBean.getOutline());
		}
		log.info(courseOutLineBean);
		CourseEvaluationBean assessmentBean = getCourseService().getEvaluationByCourseId(bean.getId());
		if(assessmentBean != null && assessmentBean.getContents() != null && assessmentBean.getContents().endsWith(".txt"))
			showEditEvaluation = true;
		else if(assessmentBean != null && assessmentBean.getContents() != null){
			showEditEvaluation = false ;
			String savePath = getOutlineFilePath();
			savePath += assessmentBean.getContents();
			String evaluPath  = CCPContants.copyOutline(savePath, assessmentBean.getContents(),Contants.EVALUATION_DERECT);
			log.info("------------evaluPath = "+evaluPath);
			HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
			session.setAttribute(CCPContants.EVALUA_FILE_PATH, assessmentBean.getContents());
		}
		
		return UPDATE;
	}
	
	private void initData(){
		Map<String, String> varMap = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
		String id = varMap.get("courseId");
		bean = getCourseService().getBeanById(id);
		if(bean.getImage()  != null && !"".equalsIgnoreCase(bean.getImage().trim())){
			File sourseFile = null;
			if(bean.getFile_path_id() !=  -1)
				sourseFile = new File(getFilePathService().findFilePathById(bean.getFile_path_id()).getPath()+bean.getImage());
			else
				sourseFile = new File(CCPContants.SYS_PATH+"files"+File.separator + bean.getImage());
			
			File des = new File(CCPContants.SYS_PATH + "tempfile"+File.separator+CCPContants.getUserBean().getId() + File.separator);
			if(des.mkdir()){
				des.mkdirs();
			}
			des = new File(CCPContants.SYS_PATH + "tempfile"+File.separator+CCPContants.getUserBean().getId()  + File.separator +sourseFile.getName());
			CCPContants.copyFile(sourseFile.getPath(), des.getPath());
			bean.setImage(CCPContants.getCurrUserId()+"/"+des.getName());
		}
		markedList = getSelectCourseService().getMarkedList(  id);
		log.info("-------goApproval()-------"+bean);
		approveList = getCourseService().getCourseApproveList(id);
		courseChapterList = null;
		Object obj = getCourseService().getCourseApprovalOpinion(id);
		approvalOpinion = obj != null ? obj.toString() : "" ;
	}
	
	public String goApprovalFromCourse(){
		initData();
		return UPDATE_RELEASE_APPROVAL;
	}
	
	public String backFromContents(){
		initData();
		return MAIN;
	} 
	
	
	public String showCourseContent(){
		Map<String, String> varMap = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
		String chapterId = varMap.get("chapterId");
		courseId = varMap.get("courseId");
		log.info("---------courseId = "+courseId);
		log.info("---------chapterId = "+chapterId);
		courseContentBean = getCourseContentService().getCourseContentBean(chapterId);
		log.info("---------courseContentBean = "+courseContentBean);
		if(courseId == null)
			courseId = courseContentBean.getCourse_id();
		HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		int index =  courseContentBean.getSection_file_url().lastIndexOf(".");
		String fileType = courseContentBean.getSection_file_url().substring(index+1,courseContentBean.getSection_file_url().length());
		log.info("-----------fileType = "+fileType);
		String path = null;
		if("zip".equalsIgnoreCase(fileType)){
			path = "/"+ courseContentBean.getSection_file_name() + "/"+  courseContentBean.getSection_file_name()  + ".htm";
			File uFile = new File(System.getProperty("webapp.root") + "tempfile"+path);
			if(uFile.exists())
				session.setAttribute(CCPContants.VIDEO_FILE_NAME, path);
			else
				session.setAttribute(CCPContants.VIDEO_FILE_NAME, "/"+ courseContentBean.getSection_file_name() + "/"+  courseContentBean.getSection_file_name()  + ".html");
		}else {
			path = 	CCPContants.getFilePath(courseContentBean.getSection_file_url() , getFilePathService(),courseContentBean.getFilePathId(),CCPContants.getUserBean().getId());
			String filePath = CCPContants.getCurrUserId()+"/"+(new File(path)).getName();
			log.info("---------filePath = "+filePath);
			session.setAttribute(CCPContants.VIDEO_FILE_NAME, filePath);
		}
		log.info("---------path = "+path);
		
		session.setAttribute(CCPContants.FILE_TYPE, fileType);
		String title = "【"+courseContentBean.getCourse_name()+"-"+courseContentBean.getChapter_title()+"-"+courseContentBean.getSection_file_name()+"】";
		if(title.length() > 30)
			title  = title.substring(0, 30) + "...";
		session.setAttribute(CCPContants.COURSE_NAME, title);
		log.info("【"+courseContentBean.getCourse_name()+"-"+courseContentBean.getChapter_title()+"】");
		int len = arrayId.length;
		for(int i=0 ; i<len; i++){
			if(chapterId.equalsIgnoreCase(arrayId[i])){
				curIndex = i;
				break;
			}
		}
		if(fileType.equalsIgnoreCase("swf") && courseContentBean.getSection_file_type().equalsIgnoreCase("swf"))
			return DEFAULT_SWF_URL;
		
		
		if(fileType.equalsIgnoreCase("swf") || fileType.equalsIgnoreCase("pdf"))
			return SWF_FILE;
		else{
			
			if("flv".equalsIgnoreCase(fileType))
				return FLV_URL;
			
			if(CCPContants.DEFAULT_VEDIO_FILE_TYPE.indexOf(fileType) >= 0){
				if("ogv".equalsIgnoreCase(fileType))
					fileType = "ogg";
				session.setAttribute(CCPContants.VIDEO_FILE_TYPE, fileType);
				log.info("---------default vedio file-------");
				return DEFAULT_VEDIO_FILE;
			}else
				return VEDIO_FILE;
		}
	}
 
	/**
	 * 
	 * @param agree
	 */
	private void doApproval(boolean agree){
		UserBean userBean = CCPContants.getUserBean();
		CourseReleaseRecordBean bo = new CourseReleaseRecordBean();
		bo.setCoursesId(bean.getId());
		bo.setApproveUserId(String.valueOf(userBean.getId()));
		bo.setApproveStatus(agree);
		bo.setApprovalOpinion(approvalOpinion);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		bo.setApproveTime(sdf.format(new Date()));
		 getCourseService().doApprove(agree, bo);
	}
	
	/**
	 * 同意
	 * @return
	 */
	public String doAgree(){
		log.info("-------doAgree()-------"+bean.getId());
		log.info(approvalOpinion);
		doApproval(true);
		return MAIN;
	}
	
 	
	/**
	 * 不同意
	 * @return
	 */
	public String doNoAgree(){
		log.info("-------doNoAgree()-------"+bean.getId());
		log.info(approvalOpinion);
		doApproval(false);
		return MAIN;
	}
	
	
	@Override
	public void getpagedetail() {
		setItemCount(getCourseService().getCountReleaseApproval());
		int currentpage = getCurrentPage();
		int pagesize = getPageSize();
		int start = (currentpage - 1) * pagesize;
		courseList = getCourseService().pageQueryForReleaseApproval(start, pagesize);
	}
 
	 

	public List<CourseBean> getCourseList() {
			getpagedetail();
		return courseList;
	}

	public void setCourseList(List<CourseBean> courseList) {
		this.courseList = courseList;
	}

	public CourseBean getBean() {
		if(bean == null)
			bean = new CourseBean();
		return bean;
	}

	public void setBean(CourseBean bean) {
		this.bean = bean;
	}

	public String getApprovalOpinion() {
		return approvalOpinion;
	}

	public void setApprovalOpinion(String approvalOpinion) {
		this.approvalOpinion = approvalOpinion;
	}
	public List<CourseContentManageBean> getCourseChapterList() {
		if(courseChapterList == null && bean.getId() != null && !bean.getId().equals("")){
			List<String> tmpList = new ArrayList<String>();
//			List<CourseContentBean> zList = getCourseContentService().getZhangeJieCourseList(bean.getId());
//			courseChapterList = new ArrayList<CourseContentManageBean>();
//			CourseContentManageBean ccmb = null ;
//			for (int i = 0; i < zList.size(); i++) {
//				CourseContentBean ccb = zList.get(i);
//				ccmb = new CourseContentManageBean(); 
//				ccmb.setChapter_number(ccb.getChapter_number());
//				ccmb.setTitle1(ccb.getChapter_title(), i ,ccb.getChapter_number());
//				ccmb.setTitle2(i);
//	//			ccmb.getCcList().add(ccb);
//				//判断章节是否有课程内容
//				List<CourseContentBean> zcList = getCourseContentService().getXiaoJieCourseList(bean.getId(),ccb.getChapter_number() ,true);
//				for(CourseContentBean bean : zcList){
//					ccmb.getCcList().add(bean);
//					tmpList.add(""+bean.getId());
//				}
//				List<CourseContentBean> xcList = getCourseContentService().getXiaoJieCourseList(bean.getId(),ccb.getChapter_number() ,false);
//				List<CourseContentManageBean> xccmbL = new ArrayList<CourseContentManageBean>();
//				CourseContentManageBean xccmb = new CourseContentManageBean();
//				String upNumber = "";
//				for(CourseContentBean bean : xcList){
//					tmpList.add(""+bean.getId());
//					if(upNumber.equals("") || upNumber.equals(bean.getChapter_number())){
//						xccmb.setXtitle(""+bean.getId(), bean.getChapter_title(), bean.getChapter_number());
//						xccmb.getCcmList().add(bean);
//					}else{
//						xccmbL.add(xccmb);
//						xccmb = new CourseContentManageBean();
//						xccmb.setXtitle(""+bean.getId(), bean.getChapter_title(), bean.getChapter_number());
//						xccmb.getCcmList().add(bean);
//					}
//					upNumber = bean.getChapter_number();
//				}
//				xccmbL.add(xccmb);
//				ccmb.setXjMList(xccmbL);
//				courseChapterList.add(ccmb);
//			}
			
			List<CourseContentBean> zList = getCourseContentService().getCourseContentList(bean.getId());
			courseChapterList = new ArrayList<CourseContentManageBean>();
			CourseContentManageBean firstLevelBean = null;//章节bean
			CourseContentManageBean secondLevelBean = null;//小节节bean
			String secondTitle = "";
			for(CourseContentBean b : zList){
				if(b.getSection_file_name() != null && !"".equalsIgnoreCase(b.getSection_file_name()))
					tmpList.add(""+b.getId());
					
				if(firstLevelBean == null){
					firstLevelBean =  addFirstLevel(b,courseChapterList,false);
				}else{
					if(b.getChapter_number().equalsIgnoreCase(firstLevelBean.getChapter_number())){//一个章节的内容
						if("0".equalsIgnoreCase(b.getStatus())){//章节下面的课程内容
							firstLevelBean.getCcList().add(b);
						}else{
							if(secondLevelBean == null){//小节bean为空
								secondLevelBean = addSecondLevel(b,false);
								firstLevelBean.getXjMList().add(secondLevelBean);
								secondTitle = b.getChapter_title();
								continue;
							}
							
							if(secondTitle.equals(b.getChapter_title())){//同一小节的课程内容
								secondLevelBean.getCcmList().add(b);
							}else{//不是一个小节的内容，则创建新的小节
								secondLevelBean = addSecondLevel(b,false);
								firstLevelBean.getXjMList().add(secondLevelBean);
								secondTitle = b.getChapter_title();
							}
							
						}
						
					}else{//不是一个章节的内容，添加一个新的章节目录
						firstLevelBean =  addFirstLevel(b,courseChapterList,false);
						secondLevelBean = null;
					}
					
				}
			}
			
			
			arrayId = new String[tmpList.size()];
			for (int i = 0; i < tmpList.size(); i++) {
//				log.info("==========="+tmpList.get(i));
				arrayId[i] = tmpList.get(i);
			}
		}
		if(courseChapterList == null)
			courseChapterList = new ArrayList<CourseContentManageBean>();
		return courseChapterList;
	}

	public void setCourseChapterList(List<CourseContentManageBean> courseChapterList) {
		this.courseChapterList = courseChapterList;
	}

	public CourseContentBean getCourseContentBean() {
		if(courseContentBean == null)
			courseContentBean = new CourseContentBean();
		return courseContentBean;
	}

	public void setCourseContentBean(CourseContentBean courseContentBean) {
		this.courseContentBean = courseContentBean;
	}

	public List<CoursesApproveBean> getApproveList() {
		if(approveList == null)
			approveList = new ArrayList<CoursesApproveBean>();
		return approveList;
	}

	public void setApproveList(List<CoursesApproveBean> approveList) {
		this.approveList = approveList;
	}

	public List<StudentMarkedHistoryBean> getMarkedList() {
		return markedList;
	}

	public String getCourseId() {
		return courseId;
	}

	public void setCourseId(String courseId) {
		this.courseId = courseId;
	}

	private String getOutlineFilePath(){
		FilePathBean path = getFilePathService().getFlagBean();
		String savePath = CCPContants.SYS_PATH+"files"+File.separator ;
		if(path != null){
			savePath = path.getPath() ;
		}
		return savePath;
	}
	
	public String getOutline() {
		outline = null; 
		CourseOutlineBean courseOutLineBean = null ;
		if(courseOutLineBean == null &&  bean != null)
			courseOutLineBean = getCourseService().getOutlineByCourseId(bean.getId());
		if(courseOutLineBean != null){
			if(courseOutLineBean.getOutline().toUpperCase().endsWith(".TXT")){
				String savePath = getOutlineFilePath();
				savePath += courseOutLineBean.getOutline();
				log.info(savePath);
				BufferedReader reader = null;
				StringBuffer buf = new StringBuffer();
				try {
					reader = new BufferedReader(new FileReader(savePath));
					String text = null;
					while ((text = reader.readLine()) != null){
						 buf.append(text);
						 buf.append(System.getProperty("line.separator"));
					}
					outline = buf.toString();
				} catch (IOException e) {
					log.info("read outline failed : ",e);
				} finally{
					try {
						if(reader != null)
							reader.close();
					} catch (IOException e) {
					}
				} 
			}
		}
		return outline;
	}

	public void setOutline(String outline) {
		this.outline = outline;
	}

	public String getCourseEva() {
		courseEva = null; 
		CourseEvaluationBean assessmentBean = null;
		if(assessmentBean == null && bean != null)
			assessmentBean = getCourseService().getEvaluationByCourseId(bean.getId());
		if(assessmentBean != null){
			if(assessmentBean.getContents().toUpperCase().endsWith(".TXT")){
				String savePath = getOutlineFilePath();
				savePath += assessmentBean.getContents();
				log.info(savePath);
				BufferedReader reader = null;
				StringBuffer buf = new StringBuffer();
				try {
					reader = new BufferedReader(new FileReader(savePath));
					String text = null;
					while ((text = reader.readLine()) != null){
						 buf.append(text);
						 buf.append(System.getProperty("line.separator"));
					}
					courseEva = buf.toString();
				} catch (IOException e) {
					log.info("read outline failed : ",e);
				} finally{
					try {
						if(reader != null)
							reader.close();
					} catch (IOException e) {
					}
				} 
			}
		}
		return courseEva;
	}

	public void setCourseEva(String courseEva) {
		this.courseEva = courseEva;
	}

	public boolean isShowEditOutline() {
		return showEditOutline;
	}

	public void setShowEditOutline(boolean showEditOutline) {
		this.showEditOutline = showEditOutline;
	}

	public boolean isShowEditEvaluation() {
		return showEditEvaluation;
	}

	public void setShowEditEvaluation(boolean showEditEvaluation) {
		this.showEditEvaluation = showEditEvaluation;
	}
	public String getStrNextCourseDetailId() {
		if(curIndex + 1 < arrayId.length)
			strNextCourseDetailId = arrayId[curIndex +1 ];
		else
			strNextCourseDetailId = "-1";
		return strNextCourseDetailId;
	}

	public void setStrNextCourseDetailId(String strNextCourseDetailId) {
		this.strNextCourseDetailId = strNextCourseDetailId;
	}

	public String getStrProCourseDetailId() {
		if(curIndex - 1 >= 0)
			strProCourseDetailId = arrayId[curIndex - 1 ];
		else
			strProCourseDetailId = "-1";
		return strProCourseDetailId;
	}

	public void setStrProCourseDetailId(String strProCourseDetailId) {
		this.strProCourseDetailId = strProCourseDetailId;
	}

	public int getCurIndex() {
		return curIndex;
	}

	public void setCurIndex(int curIndex) {
		this.curIndex = curIndex;
	}

	public String[] getArrayId() {
		return arrayId;
	}

	public void setArrayId(String[] arrayId) {
		this.arrayId = arrayId;
	}
}
